package com.cloudlead.plugin.scheduler;

import com.cloudlead.plugin.scheduler.service.ScheduleJobInstanceService;
import com.cloudlead.plugin.scheduler.service.ScheduleJobService;
import com.cloudlead.plugin.scheduler.vo.ScheduleJob;
import com.cloudlead.plugin.scheduler.vo.ScheduleJobInstance;
import com.cloudlead.plugin.scheduler.vo.dict.JobInstanceStatus;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import com.cloudlead.utils.scheduler.ScheduledTaskService;

public class ScheduleJobListener implements JobListener {

	private static final String JOB_INSTANCE_ID_PARAM = "jobInstanceId";

	@Override
	public String getName() {
		return "scheduleJob";
	}

	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		try {
			ApplicationContext ctx = (ApplicationContext) context
					.getScheduler().getContext()
					.get(ScheduledTaskService.SPRING_CONTEXT_KEY);
			ScheduleJobInstanceService jobInstanceService = ctx
					.getBean(ScheduleJobInstanceService.class);
			JobDataMap jobDataMap = context.getMergedJobDataMap();

			// 创建计划任务实例
			ScheduleJobInstance vo = new ScheduleJobInstance();
			vo.setStartTime(System.currentTimeMillis());
			vo.setStatus(JobInstanceStatus.waiting);
			vo.setJob((ScheduleJob) jobDataMap
					.get(ScheduleJobService.SCHEDULE_JOB_PARAM));
			jobInstanceService.create(vo);
			jobDataMap.put(JOB_INSTANCE_ID_PARAM, vo.getId());

		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
		System.out.println("========================================="
				+ context);
		System.out.println("========================================="
				+ context);

	}

	@Override
	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
		try {
			ApplicationContext ctx = (ApplicationContext) context
					.getScheduler().getContext()
					.get(ScheduledTaskService.SPRING_CONTEXT_KEY);
			ScheduleJobInstanceService jobInstanceService = ctx
					.getBean(ScheduleJobInstanceService.class);
			JobDataMap jobDataMap = context.getMergedJobDataMap();
			String jobInstanceId = (String) jobDataMap
					.get(JOB_INSTANCE_ID_PARAM);

			// 更新计划任务实例
			if (null != jobInstanceId) {
				ScheduleJobInstance vo = jobInstanceService.view(jobInstanceId);
				vo.setStopTime(System.currentTimeMillis());
				if (null == jobException) {
					vo.setStatus(JobInstanceStatus.completed);
				} else {
					vo.setStatus(JobInstanceStatus.exec_error);
				}
				jobInstanceService.update(vo);
			}

		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}
}
